#include <iostream>
#include <cstring>
#include <unistd.h>
#include <fcntl.h>

using namespace std;

void SetNonBlock(int fd)
{
    // 获取文件描述符 fd 当前的文件状态标志
    int fl = fcntl(fd, F_GETFL);
    if(fl < 0) // 调用失败处理
    {
        perror("fcntl");
        return;
    }

    // 将 fd 设置为非阻塞模式
    fcntl(fd, F_SETFL, fl | O_NONBLOCK);
    cout << "set " << fd << " nonblock done!" << endl;
}


int main()
{
    char buffer[1024];
    SetNonBlock(0);
    sleep(1);
    while(true)
    {
        cout << "Please Enter: " << endl;
        ssize_t n = read(0, buffer, sizeof(buffer)-1);
        if (n > 0)
        {
            buffer[n-1] = 0;
            cout << "echo: " << buffer << endl;
        }
        else if (n == 0)
        {
            cout << "read done" << endl;
            break;
        }
        else
        {
            if (errno == EWOULDBLOCK)
            {
                cout << "0 fd data not ready, try again!" << endl;
                sleep(1);
            }
            else
            {
                cerr << "read error, n = " << n << ", errno code: " << errno << ", error str: " << strerror(errno) << endl;
            }
        }
    }

    return 0;
}